<template>
  <div class="app-container">
    <!-- 2. 引入通用表单对话框组件 -->
    <CommonFormDialog
      :dialog-title="dialogTitle"
      v-model="dialogVisible"
      :dialog-width="dialogWidth"
      :form-data="snConfForm"
      :form-rules="confRules"
      :submit-loading="submitLoading"
      @close="close"
      @cancel="cancel"
      @submit="handleFormSubmit"
      @before-close="handleDialogBeforeClose"
      ref="dialogRef"
    >
      <!-- 2.1 自定义表单项（插槽：标签的“名称”和“排序”） -->
      <template #formItems>
        <el-form-item
          :label="$t('snConf.subDeviceName')"
          prop="deviceName"
        >
          <el-input
            v-model="snConfForm.deviceName"
            :placeholder="
              $t('common.placeholderInput') + $t('snConf.subDeviceName')
            "
            clearable
            maxLength="50"
          />
        </el-form-item>
        <el-form-item
          :label="$t('snConf.subDeviceSum')"
          prop="deviceNum"
        >
          <el-input-number
            v-model="snConfForm.deviceNum"
            :placeholder="
              $t('common.placeholderInput') + $t('station.subDeviceSum')
            "
            :min="1"
            :max="99999"
          />
        </el-form-item>
        <el-form-item :label="$t('snConf.tmType')" prop="tmType">
          <el-select
            v-model="snConfForm.tmType"
            :placeholder="
              $t('common.placeholderSelect') + $t('snConf.tmType')
            "
            clearable
          >
            <el-option
              v-for="(item, index) in tscaTypeList"
              :key="index"
              :label="locale ? item.cndesc : item.endesc"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('snConf.tcType')" prop="tcType">
          <el-select
            v-model="snConfForm.tcType"
            :placeholder="$t('common.placeholderSelect') + $t('station.tcType')"
            clearable
          >
            <el-option
              v-for="(item, index) in tscaTypeList"
              :key="index"
              :label="locale ? item.cndesc : item.endesc"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          :label="$t('snConf.pkey')"
          prop="pkey"
        >
          <el-input
              disabled
            v-model="snConfForm.pkey"
            :placeholder="
              $t('common.placeholderInput') + $t('snConf.pkey')
            "
            clearable
            maxLength="50"
          />
        </el-form-item>

        <el-form-item
          :label="$t('snConf.sn')"
          prop="sn"
        >
          <el-input
              disabled
            v-model="snConfForm.sn"
            :placeholder="
              $t('common.placeholderInput') + $t('snConf.sn')
            "
            clearable
            maxLength="50"
          />
        </el-form-item>
        <!-- 可扩展：如需其他表单项（如“颜色”“描述”），直接在这里添加 -->
      </template>
    </CommonFormDialog>

    <el-card>
      <el-row>
        <el-col :span="24">
          <el-card
            >
            <!-- 数据表格 -->
            <el-button icon="plus"  @click="addConf">{{
              $t("common.add")
            }}</el-button>
            <el-button icon="search" @click="search">{{
              $t("common.search")
            }}</el-button>
            <el-button icon="upload" @click="uploadRemoteSftp">{{
                $t("common.upload")
              }}</el-button>
            <span style="color: red;margin-left: 10px;">Tips:上传后请重启协控设备!!!</span>
            <el-table
              max-height="600"
              :data="tableData"
              style="width: 100%"
              @selection-change="handleSelectionChange"
            >
              <el-table-column
                :label="$t('common.sn')"
                type="index"
                width="150"
              />
              <el-table-column
                :label="$t('snConf.subDeviceName')"
                align="center"
                prop="deviceName"
              />
              <el-table-column
                :label="$t('snConf.subDeviceSum')"
                align="center"
                prop="deviceNum"
              />
              <el-table-column
                :label="$t('snConf.tmType')"
                align="center"
                prop="tmType"
              >
                <template #default="scope">{{
                  getTcsaTypeName(scope.row.tmType)
                }}</template>
              </el-table-column>
              <el-table-column
                :label="$t('snConf.tcType')"
                align="center"
                prop="tcType"
              >
                <template #default="scope">{{
                  getTcsaTypeName(scope.row.tcType)
                }}</template></el-table-column
              >
              <el-table-column
                :label="$t('snConf.pkey')"
                align="center"
                prop="pkey"
              />
              <el-table-column
                :label="$t('snConf.sn')"
                align="center"
                prop="sn"
              />
              <el-table-column
                :label="$t('common.createTime')"
                align="center"
                prop="createTime"
              />
              <el-table-column
                :label="$t('common.updateTime')"
                align="center"
                prop="updateTime"
              />
              <el-table-column
                label="操作"
                align="center"
                width="200"
                fixed="right"
              >
                <template #default="scope">
                  <el-button
                    type="primary"
                    link
                    icon="Edit"
                    @click="updateSnConf(scope.row)"
                    >{{ $t("common.edit") }}</el-button
                  >
                  <el-button
                    type="danger"
                    link
                    icon="Delete"
                    @click="deleteConf(scope.row)"
                    >{{ $t("common.delete") }}</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
                        <!-- 分页组件 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="snConfForm.pageNum"
                v-model:page-size="snConfForm.pageSize"
                :page-sizes="[10, 20, 30, 50]"
                :total="total"
                :background="true"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import {
  getsnConfPageApi,
  addsnConfApi,
  updatesnConfApi,
  delsnConfApi,
} from "@/api/ems/gateway/snConf.ts";
import  { EmsDeviceEnum } from "@/enum/EmsDeviceEnum.ts"

import {uploadRemoteSftpApi} from "@/api/file/ems/snConfExport.ts";
import { useRoute, useRouter } from "vue-router";
import { getEnumListByType } from "@/api/enums/index.ts";
import {ElMessage, ElMessageBox} from "element-plus";
import { useI18n } from "vue-i18n";
import CommonFormDialog from "@/components/Modal/basicModal.vue"; // 引入通用组件
import { reactive, ref, onMounted, onUnmounted, watch, nextTick } from "vue";
const tableData = ref(); //表格数组
const locale = ref(window.localStorage.getItem("locale") == "zh-CN");
const route = useRoute();
const dialogWidth = ref("600px");
// 1. 对话框状态
const dialogVisible = ref(false); // 对话框是否显示
const submitLoading = ref(false); // 提交按钮加载状态
const dialogRef = ref(); // 通用对话框组件引用
const { t } = useI18n();
const total = ref(0)
const dialogTitle = ref(); // 对话框标
const snConfQueryForm = reactive({

 gatewayId: null

});
// 2. 场站新增表单数据
const snConfForm = reactive({
  deviceName: "", // 子设备中文名称
  deviceNum: 0, // 子设备数量
  gatewayId: Number(route.query.id),//所属设备Id
  tmType: 0, //遥测类型
  tcType: 0, //遥控类型
  pkey: null, //子设备Pkey
  sn: null, //子设备Sn
});
// 3. 标签表单校验规则
const confRules = reactive({
  deviceName: [
    { required: true, message: t("common.placeholderInput"), trigger: "blur" },
    { max: 50, message: t("common.inputRule"), trigger: "blur" },
  ],
  deviceNum: [
    { required: true, message: t("common.placeholderInput"), trigger: "blur" },
  ],
  tmType: [
    {
      required: true,
      message: t("common.placeholderSelect"),
      trigger: "change",
    },
  ],
  tcType: [
    {
      required: true,
      message: t("common.placeholderSelect"),
      trigger: "change",
    },
  ],
  pkey: [
    { required: true, message: t("common.placeholderInput"), trigger: "blur" },
    { max: 50, message: t("common.inputRule"), trigger: "blur" },
  ],
  sn: [
    { required: true, message: t("common.placeholderInput"), trigger: "blur" },
    { max: 50, message: t("common.inputRule"), trigger: "blur" },
  ],
});
const tscaTypeList = ref();

//根据Id获取设备列表名称
//获取枚举列表
const getEnumListByTypeList = async (stype) => {
  let res = await getEnumListByType({ type: stype });
  if (stype == EmsDeviceEnum.TSCATypeEnum) {
    tscaTypeList.value = res.data;
  }
};
//查询
const search = () => {
  getSelectPage();
};
const getSelectPage = () => {
  getsnConfPageApi(snConfQueryForm).then((res) => {
    total.value = res.data.total;
    tableData.value = res.data.records;
  });
};
// 关闭对话框时，触发 update:modelValue 事件
const close = () => {
  dialogVisible.value = false; // 通知父组件将 dialogVisible 设为 false
};
// 关闭对话框时，触发 update:modelValue 事件
const cancel = () => {
  dialogVisible.value = false; // 通知父组件将 dialogVisible 设为 false
};
//新增调出弹框
const addConf = () => {
  dialogVisible.value = true;

  Object.assign(snConfForm, {
    id:null,
    deviceName: "", // 子设备中文名称
    deviceNum: 0, // 子设备数量
    gatewayId: gatewayId.value,//所属设备Id
    tmType: 0, //遥测类型
    tcType: 0, //遥控类型
    pkey: pkey.value, //子设备Pkey
    sn: sn.value, //子设备Sn
  });
  dialogTitle.value = t("snConf.snConfAdd");
};
//修改调出弹框
const confId = ref();
const updateSnConf = (row) => {
  dialogTitle.value = t("snConf.snConfUpdate");
  dialogVisible.value = true;
  confId.value = row.id;
  Object.assign(snConfForm, row);
};
const handleDialogBeforeClose = () => {
  dialogVisible.value = false; // 通知父组件将 dialogVisible 设为 false
};
//上传模板文件到sftp远程目录
const uploadRemoteSftp = async () => {
  uploadRemoteSftpApi({gatewayId:gatewayId.value, fileName:"devconf"}).then((res) => {
    if (res.code == 200) {
      ElMessage.success(t("common.success"));

    } else {
      ElMessage.success(t("common.error"));
    }
  });
};

//提交数据
const handleFormSubmit = () => {
  if (dialogTitle.value == t("snConf.snConfAdd")) {
    console.log(snConfForm,"xx")
    addsnConfApi(snConfForm).then((res) => {
      if (res.code == 200) {
        ElMessage.success(t("common.success"));
        getSelectPage();
        dialogVisible.value = false;
      } else {
        ElMessage.success(t("common.success"));
      }
    });
  } else {
    updatesnConfApi(Object.assign(snConfForm)).then((res) => {
      if (res.code == 200) {
        ElMessage.success(t("common.success"));
        getSelectPage();
        dialogVisible.value = false;
      } else {
        ElMessage.success(t("common.success"));
      }
    });
  }
};
//删除数据
const deleteConf = (row) => {
  ElMessageBox.confirm(`是否确认删除`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    delsnConfApi(row.id).then((res) => {
      if (res.code == 200) {
        ElMessage.success(t("common.success"));
        getSelectPage();
      } else {
        ElMessage.success(t("common.error"));
      }
    });
  });

};
//根据tmtype和tctype更改
const getTcsaTypeName = (val) => {
  const matchItem = tscaTypeList.value.find((item) => item.code == val);
  return matchItem ? (locale ? matchItem.cndesc : matchItem.endesc) : null;
};
const handleSizeChange = (val) => {
  snConfForm.pageSize = val;
  getSelectPage();
};
const handleCurrentChange = (val) => {

  snConfForm.pageNum = val;
  getSelectPage();
};
const gatewayId = ref();
const pkey = ref()
const sn = ref()
onMounted(() => {
  gatewayId.value = route.query.gatewayId;
  pkey.value = route.query.pkey
  sn.value = route.query.sn
  console.log(pkey.value,sn.value,"xxx")
  snConfQueryForm.gatewayId = gatewayId.value;
  snConfForm.gatewayId = gatewayId.value;
  snConfForm.pkey = pkey.value;
  snConfForm.sn = sn.value;
  //获取四遥信号发送类型
  getEnumListByTypeList("tscaType");
  getSelectPage();
});
onUnmounted(() => {});
</script>
<style lang="scss" scoped>
:deep(.dv-scroll-board .header) {
  background: #ddd !important;
}
:deep(.dv-scroll-board .rows .row-item) {
  background: gray !important;
}
</style>
